package app

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"yxService/app/pkg/errcode"
)

type Response struct {
	Ctx *gin.Context
}

type Pager struct {
	Page      int `json:"page"`
	PageSize  int `json:"page_size"`
	TotalRows int `json:"total_rows"`
}

func NewResponse(ctx *gin.Context) *Response {
	return &Response{Ctx: ctx}
}

func (r *Response) ToResponse(data interface{}, err *errcode.Error) {
	data = gin.H{
		"data": data,
		"code": err.Code(),
		"msg":  err.Msg(),
	}

	r.Ctx.JSON(http.StatusOK, data)
}

func (r *Response) ToResponseList(list interface{}, totalRows int, err errcode.Error) {
	data := make(map[string]interface{})
	data["list"] = list
	data["pager"] = Pager{
		Page:      GetPage(r.Ctx),
		PageSize:  GetPageSize(r.Ctx),
		TotalRows: totalRows,
	}
	r.Ctx.JSON(err.StatusCode(), gin.H{
		"data": data,
		"code": err.Code(),
		"msg":  err.Msg(),
	})
}

func (r *Response) ToErrorResponse(err error, errCode *errcode.Error) {

	var data interface{}
	if err != nil {
		data = err.Error()
	}
	response := gin.H{
		"data": data,
		"code": errCode.Code(),
		"msg":  errCode.Msg(),
	}
	r.Ctx.JSON(errCode.StatusCode(), response)
}
